import os
import sys

from PySide6.QtCore import QThread, Signal


class ModelLoader(QThread):
    """后台加载模型的线程"""
    loading_finished = Signal(bool, str)  # (success, message)

    def __init__(self):
        super().__init__()
        self.model_loaded = False

    def run(self):
        try:
            # 延迟导入，避免启动时加载模型
            from paddleocr import PaddleOCR
            import os
            import sys

            # 确定模型目录路径
            if getattr(sys, 'frozen', False):
                # 打包环境 - 模型在gui/models目录下
                base_path = os.path.dirname(sys.executable)
                models_dir = os.path.join(base_path, 'models')
                print('模型目录:', models_dir)
            else:
                # 开发环境 - 模型在当前目录的gui/models下
                models_dir = os.path.join(os.path.dirname(__file__), 'models')
                print('模型目录:', models_dir)

            if self.contains_chinese(models_dir):
                self.loading_finished.emit(False, f"路径不要包含中文字符")
                return


            # 指定各个模型的完整路径
            det_model_dir = os.path.join(models_dir, 'ch_PP-OCRv4_det_infer')
            rec_model_dir = os.path.join(models_dir, 'ch_PP-OCRv4_rec_infer')
            cls_model_dir = os.path.join(models_dir, 'ch_ppocr_mobile_v2.0_cls_infer')

            # 加载OCR模型
            self.ocr = PaddleOCR(
                use_angle_cls=True,
                lang="ch",
                use_gpu=False,
                det_model_dir=det_model_dir,
                rec_model_dir=rec_model_dir,
                cls_model_dir=cls_model_dir,
                download_models=False,
            )

            self.model_loaded = True
            self.loading_finished.emit(True, "模型加载完成")
        except Exception as e:
            self.loading_finished.emit(False, f"模型加载失败: {str(e)}")

    # 检查路径是否包含中文
    def contains_chinese(self, path):
        for char in path:
            if '\u4e00' <= char <= '\u9fff':
                return True
        return False

